//
//  SelectList.m
//  Trading365
//
//  Created by yifei tong on 12-2-8.
//  Copyright (c) 2012年 dhc. All rights reserved.
//

#import "QuotMultSelectList.h"
#import "TaskManager.h"
#import "XmlRpc.h"
#import "Session.h"
#import "InfoType.h"


@implementation QuotMultSelectList
@synthesize table;
@synthesize multSelectBeginBlcok;
@synthesize lastSelectIDs;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)init
{
	self = [super init];
	if(self)
	{
        responseParams = [[NSMutableArray alloc] initWithCapacity:0];
        indexpathDic = [[NSMutableDictionary alloc] initWithCapacity:0];
        selectProductArray = [[NSMutableArray alloc] initWithCapacity:0];
//        lastSelectIDs = [[NSMutableArray alloc] initWithCapacity:0];
	}
	
	return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [lastSelectIDs release];
    [table release];
//    [search release];
    [super dealloc];
}

- (void)initMultSelectBeginBlcok:(MultSelectBeginBlcok) multSelectBeginBlcok1
{
    self.multSelectBeginBlcok=multSelectBeginBlcok1;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [self init];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.search.showsCancelButton=NO;
    
//    UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
//                                   initWithTitle:@"返回" 
//                                   style:UIBarButtonItemStyleDone
//                                   target:self
//                                   action:@selector(goBack:)];
//    self.navigationItem.leftBarButtonItem = saveButton;
//    [saveButton release];
    
    [self refreshData];
    [self.table reloadData];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    table=nil;
//    search = nil;
    
    [[[TaskManager Share] GetTaskByType:GetQuotMultSelectList Delegate:self] cancel];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - Table view data source

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [responseParams count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = (UITableViewCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                       reuseIdentifier: CellIdentifier] autorelease];
    }
    if (indexPath.row>[responseParams count]) {
        return cell;
    }
    
    NSUInteger row1 = [indexPath row];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:18];
    
    NSMutableDictionary* tmp_dictionary = nil;
    if (row1 < [responseParams count]) 
    {
        tmp_dictionary = [[NSMutableDictionary alloc] initWithDictionary:[responseParams objectAtIndex:row1]];
    }else
    {
        tmp_dictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
    }

    //产品列表
    if (infotype == INFO_TYPE_PRODUCT) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"product_name_ch"];        
    }
    
//    for (NSString *ids in lastSelectIDs){
//        if ([[tmp_dictionary objectForKey:@"id"] isEqualToString:ids]){
//            cell.accessoryType=UITableViewCellAccessoryCheckmark;
//            [cell setBackgroundColor:[UIColor clearColor]];
//            [cell setHighlighted:YES];
//            [cell setSelected:YES];
//        }
//    }
    
    [tmp_dictionary release];

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{   
    NSString *rowstr = [NSString stringWithFormat:@"%i",indexPath.row];
    UITableViewCell *Cell = [tableView cellForRowAtIndexPath:indexPath];
    Cell.accessoryType = UITableViewCellAccessoryNone;
    
    if([indexpathDic objectForKey:rowstr]) {
        [indexpathDic removeObjectForKey:rowstr];
    } else {
        //NSLog(@"not in");
        Cell.accessoryType = UITableViewCellAccessoryCheckmark;
        NSMutableDictionary* dic = nil;
        if (indexPath.row < [responseParams count]) 
        {
            dic = [[NSMutableDictionary alloc] initWithDictionary:[responseParams objectAtIndex:indexPath.row]];
        }else
        {
            dic = [[NSMutableDictionary alloc] initWithCapacity:0];
        }
        
        [indexpathDic setObject:dic forKey:rowstr];
        [dic release];
    }
        
    //点击条目即返回
//    [self.navigationController popViewControllerAnimated:YES];
//    NSLog(@"[[InfoType share] SetTranValueDict]=%@",[[InfoType share] GetTranValueDict]);

}

#pragma mark - 
#pragma mark - my function
- (void)doSearch{
    [super doSearch];
    //
    [self.table reloadData];
    
    [[[TaskManager Share] GetTaskByType:GetQuotMultSelectList Delegate:self] Excute];
    
}


-(void)AddArray
{
    
    for(id key in indexpathDic)
    {
        NSMutableDictionary *dict_tmp = [[NSMutableDictionary alloc] initWithCapacity:0];
        [dict_tmp setValue:[[indexpathDic objectForKey:key] objectForKey:@"id"] forKey:@"product_id"];
        [dict_tmp setValue:[[indexpathDic objectForKey:key] objectForKey:@"product_name_ch"] forKey:@"product_name_ch"];
        [dict_tmp setValue:[[indexpathDic objectForKey:key] objectForKey:@"purchase_unit_price"] forKey:@"purchase_unit_price"];
        [dict_tmp setValue:[[indexpathDic objectForKey:key] objectForKey:@"product_vat"] forKey:@"product_vat"];
        [dict_tmp setValue:[[indexpathDic objectForKey:key] objectForKey:@"product_bt"] forKey:@"product_bt"];
        [dict_tmp setValue:[[indexpathDic objectForKey:key] objectForKey:@"unit"] forKey:@"basic_unit"];
        [selectProductArray addObject:dict_tmp];
        [dict_tmp release];
    }
}

-(void)SetInfoType:(int)type
{
    infotype = type;
}

-(void)refreshData
{
     //设置标题
    if (infotype == INFO_TYPE_PRODUCT){
        self.title = INFO_STRING_PRODUCT;
    }

    [[[TaskManager Share] GetTaskByType:GetQuotMultSelectList Delegate:self] Excute];
}

-(void) getMoreData
{
    [[[TaskManager Share] GetTaskByType:GetQuotMultSelectList Delegate:self] Excute];
}

-(void) OnPreExcute
{
    [super OnPreExcute];
}

-(void) DoInBackground
{
    if (getflag == NO && _isSearching == NO) {
        return;
    }
    startRow = [responseParams count];
    NSString *num = [[NSString alloc] initWithFormat:@"%i",startRow];
    NSString *rowsperpage = [NSString stringWithFormat:@"%i",PER_PAGE_ROWS];
    NSMutableArray *tmp=nil;
    XmlRpc *xml = [[XmlRpc alloc] init];
    
    switch (infotype) {
        case INFO_TYPE_PRODUCT:     //产品信息
        {   
            if (_isSearching){
                tmp = [xml GetSearchProductList:[[Session share] getMemberID] searchCondition:p_search searchType:@"01" startRows:num rowsPerPage:rowsperpage];                
            }else{
                tmp = [xml GetProductList:[[Session share] getMemberID] startRows:num rowsPerPage:rowsperpage];
            }
            break;
        }    

        default:
            break;
    }
        
    for (NSMutableDictionary* itq in tmp) {
        [responseParams addObject:itq];
    }
    if ([tmp count]<PER_PAGE_ROWS) {
        getflag = NO;
    }
    [xml release];
    [num release];
    
    [self.table reloadData];
}

-(void) OnPostExcute
{
    [super OnPostExcute];
}

//- (IBAction)goBack:(id)sender
//{
//    [self AddArray];
//    
//    if (self.multSelectBeginBlcok != nil) {
//        self.multSelectBeginBlcok(selectProductArray);
//    }
//    
//    [self.navigationController popViewControllerAnimated:YES];
//}
- (IBAction)goBack
{
    [self AddArray];
    
    if (self.multSelectBeginBlcok != nil) {
        self.multSelectBeginBlcok(selectProductArray);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}


@end
